package shopping.demo.controller;

import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import shopping.demo.code.ResponseCode;
import shopping.demo.entities.response.Response;
import shopping.demo.entities.User;
import shopping.demo.service.UserService;
import shopping.demo.util.TokenUtils;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/index")
public class LoginController {
    private Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    private UserService userService;
    @Autowired
    private TokenUtils tokenUtils;

    @GetMapping("/login")
    public String toIndex(){
        JSONObject response = new JSONObject();
        response.put("code", ResponseCode.LOGIN_SUCCESS.getCode());

        return response.toJSONString();
    }

    //post方法是提交表单信息，交由spring security进行一个权限处理
    @PostMapping(value = "/login",consumes = "application/json")
    public String check(@RequestBody JSONObject jsonObject,
                        HttpServletRequest request) {
        Long userId = jsonObject.getLong("userId");
        String password = jsonObject.getString("password");

        User user = userService.findByUserId(userId);
        logger.info("用户" + userId + "登陆中....");
        JSONObject response = new JSONObject();
        //验证、授权阶段
        if(user.getPassword().equals(password)) {
            //检验成功，将username加入Session
            request.getSession().setAttribute("username", user.getUsername());

            response.put("code", ResponseCode.LOGIN_SUCCESS.getCode());
            response.put("msg", ResponseCode.LOGIN_SUCCESS.getMsg());
            response.put("username", user.getUsername());
            response.put("money", user.getMoney());
            response.put("role", user.getRole());
        }else {
            response.put("code",ResponseCode.LOGIN_FAIL.getCode());
            response.put("msg",ResponseCode.LOGIN_FAIL.getMsg());
        }


        return response.toJSONString();
    }


    @GetMapping("/logout")
    public String toLogout(HttpServletRequest request){
        //退出登录

        //删除session对应缓存
        request.getSession().removeAttribute("username");
        return JSONObject.toJSONString(new Response(ResponseCode.LOGOUT_SUCCESS.getCode(),ResponseCode.LOGOUT_SUCCESS.getMsg()));
    }

    @GetMapping("/token")
    public String token() {
        return tokenUtils.createToken();
    }

}
